<template>
  <div class="analytics-page">
    <div class="container-fluid py-4">
      <!-- 页面标题 -->
      <div class="d-flex justify-content-between align-items-center mb-4">
        <h2 class="mb-0">数据分析</h2>
        <div class="time-range-selector">
          <select class="form-select" v-model="selectedTimeRange" @change="handleTimeRangeChange">
            <option value="7">最近7天</option>
            <option value="30">最近30天</option>
            <option value="90">最近3个月</option>
            <option value="365">最近一年</option>
          </select>
        </div>
      </div>

      <!-- 销售关键指标 -->
      <div class="row mb-4">
        <div class="col-xl-3 col-md-6 mb-4">
          <div class="card border-left-primary shadow h-100 py-2">
            <div class="card-body">
              <div class="row no-gutters align-items-center">
                <div class="col mr-2">
                  <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">
                    总销售额
                  </div>
                  <div class="h5 mb-0 font-weight-bold text-gray-800">
                    {{ formatPrice(salesMetrics.totalSales) }}
                  </div>
                </div>
                <div class="col-auto">
                  <i class="fas fa-dollar-sign fa-2x text-gray-300"></i>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="col-xl-3 col-md-6 mb-4">
          <div class="card border-left-success shadow h-100 py-2">
            <div class="card-body">
              <div class="row no-gutters align-items-center">
                <div class="col mr-2">
                  <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                    订单总数
                  </div>
                  <div class="h5 mb-0 font-weight-bold text-gray-800">
                    {{ salesMetrics.totalOrders }}
                  </div>
                </div>
                <div class="col-auto">
                  <i class="fas fa-shopping-cart fa-2x text-gray-300"></i>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="col-xl-3 col-md-6 mb-4">
          <div class="card border-left-info shadow h-100 py-2">
            <div class="card-body">
              <div class="row no-gutters align-items-center">
                <div class="col mr-2">
                  <div class="text-xs font-weight-bold text-info text-uppercase mb-1">
                    平均订单价值
                  </div>
                  <div class="h5 mb-0 font-weight-bold text-gray-800">
                    {{ formatPrice(salesMetrics.averageOrderValue) }}
                  </div>
                </div>
                <div class="col-auto">
                  <i class="fas fa-chart-bar fa-2x text-gray-300"></i>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 支付方式统计 -->
        <div class="col-xl-6 col-lg-6">
          <div class="card shadow mb-4">
            <div class="card-header py-3">
              <h6 class="m-0 font-weight-bold text-primary">支付方式统计</h6>
            </div>
            <div class="card-body">
              <div v-if="loadingPayType" class="text-center py-3">
                <div class="spinner-border text-primary" role="status"></div>
              </div>
              <div v-else-if="payTypeData.length > 0">
                <div 
                  class="payment-method-item d-flex justify-content-between align-items-center mb-3"
                  v-for="item in payTypeData"
                  :key="item.name"
                >
                  <div class="method-info">
                    <span class="method-name">{{ item.name }}</span>
                  </div>
                  <div class="method-stats">
                    <span class="badge bg-primary">{{ item.value }}%</span>
                  </div>
                </div>
              </div>
              <div v-else class="text-center text-muted py-3">
                暂无支付数据
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- 图表区域 -->
      <div class="row">
        <!-- 用户统计 -->
        <div class="col-xl-6 col-lg-6">
          <div class="card shadow mb-4">
            <div class="card-header py-3">
              <h6 class="m-0 font-weight-bold text-primary">用户统计</h6>
            </div>
            <div class="card-body">
              <div v-if="loadingUserStats" class="text-center py-3">
                <div class="spinner-border text-primary" role="status"></div>
              </div>
              <div v-else-if="userStats">
                <div class="user-stat-item d-flex justify-content-between align-items-center mb-3">
                  <span>总用户数</span>
                  <span class="badge bg-info">{{ userStats.totalUsers }}</span>
                </div>
                <div class="user-stat-item d-flex justify-content-between align-items-center mb-3">
                  <span>活跃用户</span>
                  <span class="badge bg-success">{{ userStats.activeUsers }}</span>
                </div>
                <div class="user-stat-item d-flex justify-content-between align-items-center mb-3">
                  <span>新增用户</span>
                  <span class="badge bg-primary">{{ userStats.newUsers }}</span>
                </div>
                <div class="user-stat-item d-flex justify-content-between align-items-center" v-if="userStats.totalFavorites">
                  <span>总收藏数</span>
                  <span class="badge bg-info">{{ userStats.totalFavorites }}</span>
                </div>
              </div>
              <div v-else class="text-center text-muted py-3">
                暂无用户数据
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 商品统计 -->
      <div class="row">
        <div class="col-12">
          <div class="card shadow mb-4">
            <div class="card-header py-3">
              <h6 class="m-0 font-weight-bold text-primary">商品统计</h6>
            </div>
            <div class="card-body">
              <div v-if="loadingProductStats" class="text-center py-3">
                <div class="spinner-border text-primary" role="status"></div>
              </div>
              <div v-else-if="productStats">
                <div class="row">
                  <div class="col-md-3 col-sm-6 mb-3">
                    <div class="text-center">
                      <div class="h4 text-primary">{{ productStats.totalProducts }}</div>
                      <div class="text-muted">商品总数</div>
                    </div>
                  </div>
                  <div class="col-md-3 col-sm-6 mb-3">
                    <div class="text-center">
                      <div class="h4 text-success">{{ productStats.onsaleProducts }}</div>
                      <div class="text-muted">在售商品</div>
                    </div>
                  </div>
                  <div class="col-md-3 col-sm-6 mb-3">
                    <div class="text-center">
                      <div class="h4 text-warning">{{ productStats.lowStockProducts }}</div>
                      <div class="text-muted">库存预警</div>
                    </div>
                  </div>
                </div>
              </div>
              <div v-else class="text-center text-muted py-3">
                暂无商品数据
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { Message } from '@/utils/message'

// 导入分析API
import { 
  getSaleKeyMetrics, 
  getSalePayType, 
  getProductKeyMetrics, 
  getUserStatus 
} from '@/api/analytics'
import type { TimeSearch, Sales, ProductBack, UserStatsVO } from '@/types/analytics'

// 页面状态
const loadingSales = ref(false)
const loadingPayType = ref(false)
const loadingProductStats = ref(false)
const loadingUserStats = ref(false)
const selectedTimeRange = ref('30')

// 数据状态
const salesMetrics = ref<Sales>({
  totalSales: 0,
  totalOrders: 0,
  averageOrderValue: 0,
  completionRate: 0
})

const payTypeData = ref<Array<{ name: string, value: number }>>([])
const productStats = ref<ProductBack | null>(null)
const userStats = ref<UserStatsVO | null>(null)

// 获取时间范围
const getTimeRange = (days: number): TimeSearch => {
  const endDate = new Date()
  const startDate = new Date()
  startDate.setDate(endDate.getDate() - days)
  
  return {
    startDate: startDate.toISOString().split('T')[0],
    endDate: endDate.toISOString().split('T')[0]
  }
}

// 格式化价格
const formatPrice = (price: number) => {
  if (typeof price !== 'number' || isNaN(price)) {
    return '¥0.00'
  }
  return new Intl.NumberFormat('zh-CN', {
    style: 'currency',
    currency: 'CNY'
  }).format(price)
}



// 获取销售关键指标
const fetchSalesMetrics = async () => {
  loadingSales.value = true
  try {
    const timeRange = getTimeRange(parseInt(selectedTimeRange.value))
    const response = await getSaleKeyMetrics(timeRange)
    const rawData = response.data
    
    console.log('销售指标原始数据:', rawData)
    
    // 确保数据完整性，计算缺失的字段
    const processedData: Sales = {
      totalSales: rawData.totalSales || 0,
      totalOrders: rawData.totalOrders || 0,
      averageOrderValue: rawData.averageOrderValue || 0,
      completionRate: 0
    }
    
    // 如果后端没有计算平均订单价值，前端计算
    if (processedData.averageOrderValue === 0 && processedData.totalOrders > 0) {
      processedData.averageOrderValue = processedData.totalSales / processedData.totalOrders
    }
    
    salesMetrics.value = processedData
  } catch (error) {
    console.error('获取销售指标失败:', error)
    Message.error('获取销售指标失败')
  } finally {
    loadingSales.value = false
  }
}



// 获取支付方式统计
const fetchPayTypeStats = async () => {
  loadingPayType.value = true
  try {
    const timeRange = getTimeRange(parseInt(selectedTimeRange.value))
    const response = await getSalePayType(timeRange)
    
    // 处理后端数据格式转换
    const rawData = response.data
    console.log('支付方式原始数据:', rawData)
    
    if (Array.isArray(rawData)) {
      // 转换数据格式：后端 {payType, count} -> 前端 {name, value}
      const totalCount = rawData.reduce((sum: number, item: any) => sum + (item.count || 0), 0)
      
      payTypeData.value = rawData.map((item: any) => ({
        name: item.payType || item.name || '未知',
        value: totalCount > 0 ? Math.round((item.count / totalCount) * 100) : 0
      }))
    } else {
      console.warn('支付方式数据格式异常:', rawData)
      payTypeData.value = []
    }
  } catch (error) {
    console.error('获取支付方式统计失败:', error)
    Message.error('获取支付方式统计失败')
    payTypeData.value = []
  } finally {
    loadingPayType.value = false
  }
}

// 获取商品统计
const fetchProductStats = async () => {
  loadingProductStats.value = true
  try {
    const timeRange = getTimeRange(parseInt(selectedTimeRange.value))
    const response = await getProductKeyMetrics(timeRange)
    const rawData = response.data
    
    console.log('商品统计原始数据:', rawData)
    
    // 数据验证和默认值处理 - 使用后端实际字段名
    productStats.value = {
      totalProducts: rawData.totalProducts || 0,
      onsaleProducts: rawData.onsaleProducts || 0,
      lowStockProducts: rawData.lowStockProducts || 0
    }
  } catch (error) {
    console.error('获取商品统计失败:', error)
    Message.error('获取商品统计失败')
    // 设置默认值避免显示错误
    productStats.value = {
      totalProducts: 0,
      onsaleProducts: 0,
      lowStockProducts: 0
    }
  } finally {
    loadingProductStats.value = false
  }
}

// 获取用户统计
const fetchUserStats = async () => {
  loadingUserStats.value = true
  try {
    const response = await getUserStatus()
    const rawData = response.data
    
    console.log('用户统计原始数据:', rawData)
    
    // 数据验证和默认值处理 - 使用后端实际字段
    userStats.value = {
      totalUsers: rawData.totalUsers || 0,
      activeUsers: rawData.activeUsers || 0,
      newUsers: rawData.newUsers || 0,
      genderDistribution: rawData.genderDistribution || {},
      memberLevelDistribution: rawData.memberLevelDistribution || {},
      totalFavorites: rawData.totalFavorites || 0,
      todayFavorites: rawData.todayFavorites || 0,
      totalConsumption: rawData.totalConsumption || 0,
      currentYearConsumption: rawData.currentYearConsumption || 0
    }
  } catch (error) {
    console.error('获取用户统计失败:', error)
    Message.error('获取用户统计失败')
    // 设置默认值避免显示错误
    userStats.value = {
      totalUsers: 0,
      activeUsers: 0,
      newUsers: 0,
      genderDistribution: {},
      memberLevelDistribution: {},
      totalFavorites: 0,
      todayFavorites: 0,
      totalConsumption: 0,
      currentYearConsumption: 0
    }
  } finally {
    loadingUserStats.value = false
  }
}

// 时间范围变化处理
const handleTimeRangeChange = () => {
  fetchSalesMetrics()
  fetchPayTypeStats()
  fetchProductStats()
  // 用户统计不受时间范围影响
}

// 获取所有数据
const fetchAllData = async () => {
  await Promise.all([
    fetchSalesMetrics(),
    fetchPayTypeStats(),
    fetchProductStats(),
    fetchUserStats()
  ])
}

onMounted(() => {
  fetchAllData()
})
</script>

<style scoped>
.analytics-page {
  background-color: #f8f9fa;
  min-height: 100vh;
}

.border-left-primary {
  border-left: 4px solid #007bff !important;
}

.border-left-success {
  border-left: 4px solid #28a745 !important;
}

.border-left-info {
  border-left: 4px solid #17a2b8 !important;
}

.border-left-warning {
  border-left: 4px solid #ffc107 !important;
}

.text-gray-800 {
  color: #5a5c69 !important;
}

.text-gray-300 {
  color: #dddfeb !important;
}

.font-weight-bold {
  font-weight: 700 !important;
}

.payment-method-item,
.user-stat-item {
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
}

.payment-method-item:last-child,
.user-stat-item:last-child {
  border-bottom: none;
}

.method-name {
  font-weight: 500;
}

.time-range-selector .form-select {
  width: auto;
}
</style> 